package com.sanhuo.utils.office;


import com.sanhuo.lib.ExceptionUtil;
import com.sanhuo.lib.exception.GlobalException;
import org.apache.poi.hslf.usermodel.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class OfficeUtil {
    /**
     * 读出Excel文件
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static Workbook readFile(MultipartFile file) throws IOException {
        if (file == null) {
            return null;
        }
        String fileName = file.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf("."));
        Workbook workbook = null;
        if (".xlsx".equals(ext)) {
            workbook = new XSSFWorkbook(file.getInputStream());// office2007+
        } else if (".xls".equals(ext)) {
            workbook = new HSSFWorkbook(file.getInputStream());
        } else {
            throw new GlobalException("请上传excal文件!");
        }
        return workbook;
    }

    public static Workbook readFile(File file) throws IOException {
        if (file == null) {
            return null;
        }
        String fileName = file.getName();
        String ext = fileName.substring(fileName.lastIndexOf("."));
        Workbook workbook = null;
        if (".xlsx".equals(ext)) {
            workbook = new XSSFWorkbook(new FileInputStream(file));// office2007+
        } else if (".xls".equals(ext)) {
            workbook = new HSSFWorkbook(new FileInputStream(file));
        } else {
            throw new GlobalException("请上传excal文件!");
        }
        return workbook;
    }

    /**
     * PPt转化为图片形式(2007+版本)
     *
     * @param pptFile
     * @param imgFile
     * @param list
     * @return
     */
    public static boolean pptToImg_2007(File pptFile, File imgFile, List<String> list) {
        FileInputStream is = null;
        try {
            if (!imgFile.exists()) {
                imgFile.mkdirs();
            }
            is = new FileInputStream(pptFile);
            XMLSlideShow ppt = new XMLSlideShow(is);
            is.close();
            // 获取大小
            Dimension pgsize = ppt.getPageSize();
            // 获取幻灯片
            List<XSLFSlide> slides = ppt.getSlides();
            for (int i = 0; i < slides.size(); i++) {
                // 解决乱码问题
                List<XSLFShape> shapes = slides.get(i).getShapes();
                for (XSLFShape shape : shapes) {
                    if (shape instanceof XSLFTextShape) {
                        XSLFTextShape sh = (XSLFTextShape) shape;
                        List<XSLFTextParagraph> textParagraphs = sh.getTextParagraphs();
                        for (XSLFTextParagraph xslfTextParagraph : textParagraphs) {
                            List<XSLFTextRun> textRuns = xslfTextParagraph.getTextRuns();
                            for (XSLFTextRun xslfTextRun : textRuns) {
                                xslfTextRun.setFontFamily("宋体");
                            }
                        }
                    }
                }
                //根据幻灯片大小生成图片
                BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                // 最核心的代码
                slides.get(i).draw(graphics);
                //图片将要存放的路径
                String absolutePath = imgFile.getAbsolutePath() + "/" + (i + 1) + ".jpeg";
                File jpegFile = new File(absolutePath);
                // 图片路径存放
                list.add((i + 1) + ".jpeg");
                //如果图片存在，则不再生成
                if (jpegFile.exists()) {
                    continue;
                }
                // 这里设置图片的存放路径和图片的格式(jpeg,png,bmp等等),注意生成文件路径
                FileOutputStream out = new FileOutputStream(jpegFile);
                // 写入到图片中去
                ImageIO.write(img, "jpeg", out);
            }
            return true;
        } catch (Exception e) {
            if (e.getMessage().equals("org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]")) {
                pptToImg_2003(pptFile, imgFile, list);
            } else {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 将ppt转图片(2003版)
     *
     * @param pptFile
     * @param imgFile
     * @param list
     * @return
     */
    public static Boolean pptToImg_2003(File pptFile, File imgFile, List<String> list) {
        FileInputStream is = null;
        try {
            if (!imgFile.exists()) {
                imgFile.mkdirs();
            }
            is = new FileInputStream(pptFile);
            HSLFSlideShow ppt = new HSLFSlideShow(is);
            Dimension pgsize = ppt.getPageSize();
            List<HSLFSlide> slides = ppt.getSlides();
            int i = 0;
            for (HSLFSlide slide : slides) {
                List<HSLFShape> shapes = slide.getShapes();
                for (HSLFShape shape : shapes) {
                    if (shape instanceof HSLFTextShape) {
                        HSLFTextShape sh = (HSLFTextShape) shape;
                        List<HSLFTextParagraph> textParagraphs = sh.getTextParagraphs();
                        for (HSLFTextParagraph xslfTextParagraph : textParagraphs) {
                            List<HSLFTextRun> textRuns = xslfTextParagraph.getTextRuns();
                            for (HSLFTextRun xslfTextRun : textRuns) {
                                xslfTextRun.setFontFamily("宋体");
                            }
                        }
                    }
                }
                //根据幻灯片大小生成图片
                BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                // 最核心的代码
                slide.draw(graphics);
                //图片将要存放的路径
                String absolutePath = imgFile.getAbsolutePath() + "/" + (++i) + ".jpeg";
                File jpegFile = new File(absolutePath);
                // 图片路径存放
                list.add((i) + ".jpeg");
                //如果图片存在，则不再生成
                if (jpegFile.exists()) {
                    continue;
                }
                // 这里设置图片的存放路径和图片的格式(jpeg,png,bmp等等),注意生成文件路径
                FileOutputStream out = new FileOutputStream(jpegFile);
                // 写入到图片中去
                ImageIO.write(img, "jpeg", out);
            }
            return true;
        } catch (IOException e) {
            if (e.getMessage().equals("The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)")) {
                pptToImg_2007(pptFile, imgFile, list);
            } else {
                e.printStackTrace();
            }
            return false;
        }
    }

}
